<template>
	<view :style="{
      '--distance': `-${distance}px`,
      '--distance1': `-${distance1}px`
    }">
		<!-- 父元素的宽度 -->
		<view class="aniFather" ref="cardView" style="width: 100vw" />
		<!-- 每个item的宽度 -->
		<view class="aniChild" ref="demoView" style="width: 133rpx" />

		<view v-if="showAni" class="ani-pop" :key="aniKey">
			<view class="ani-pop-hd">
				<image class="w-100" src="/static/icon/public/cj-1.png" lazy-load mode="widthFix"></image>
			</view>

			<view class="ani-pop-bd c_bg">
				<view class="dot-line">
					<view class="dot">
						<image class="w-100" src="/static/icon/public/cj-2.png" lazy-load mode="widthFix"></image>
						<image class="w-100 cc47" src="/static/icon/public/cj-3.png" mode="widthFix"></image>
					</view>

					<view class="line c_bg"></view>

					<view class="dot">
						<image class="w-100" src="/static/icon/public/cj-4.png" lazy-load mode="widthFix"></image>
						<image class="w-100 cc48" src="/static/icon/public/cj-5.png" mode="widthFix"></image>
					</view>
				</view>

				<view v-for="(item, i) in aniList" :key="i" class="row" :class="{
            move: i % 2 == 0,
            move1: i % 2 != 0
          }">
					<view v-for="(a, b) in item" :key="b" :class="['row-item',`row-item-${a.shang_id}`]">
						<view class="pic" :style="{ backgroundImage: `url(${a.imgurl})`}"></view>
						<view class="bar" :style="{background:`${updateDynamicStyles(a.shang_id,'bar')}`} "></view>
					</view>
				</view>
			</view>
			<view class="allDrawn">
				<view v-for="item in allDrawnList" class="pic" :key="item.id">
					<image :src="item.goodslist_imgurl" mode=""></image>
				</view>
			</view>

			<view class="ani-pop-ft" @click="skipAni(true)">跳过</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showAni: false,
				aniList: [],
				aniKey: 5518,
				aniTimer: null,
				distance: null,
				distance1: null,
				skipMusic: null,
				drawMusic: null,
				music_1: '/static/audio/open.mp3',
				music_2: '/static/audio/zhuan.mp3',
				allDrawnList: [],
				scrollID: 0,
				clear: false,
				previousFirstItemId: null,
				colorBack: [{
						34: 'linear-gradient(180deg, rgba(255, 158.00000578165054, 122.00000032782555, 0.5), rgba(255, 50.000000819563866, 85.0000025331974, 0.5))'
					},
					{
						35: 'linear-gradient(180deg, rgba(255, 188.0000039935112, 0, 0.5), rgba(240.00000089406967, 166.00000530481339, 0, 0.5))'
					},
					{
						36: 'linear-gradient(180deg, rgba(161.0000056028366, 155.00000596046448, 240.00000089406967, 0.5), rgba(127.00000002980232, 101.00000157952309, 229.00000154972076, 0.5))'
					},
					{
						37: 'linear-gradient(180deg, rgba(181.0000044107437, 181.0000044107437, 181.0000044107437, 0.5), rgba(146.00000649690628, 146.00000649690628, 146.00000649690628, 0.5))'
					}
				]
			}
		},
		props: ['parentTime'],
		watch: {
			clear(newVal, oldVal) {
				if (newVal == true) this.allDrawnList = []
			},
			allDrawnList(newVal, oldVal) {
				console.log('===>', newVal);
			},
		},
		mounted() {
			/* 计算 */
			this.calcDistance()

		},
		onReady() {
			/* 调用 */
			/* arr:中奖结果数组 */
			/* arr1:所有奖品数组 */
			// this.initDraw(arr, arr1)
		},
		beforeDestroy() {
			clearTimeout(this.aniTimer)
			try {
				this.drawMusic.pause()
				this.skipMusic.pause()
			} catch (e) {
				//TODO handle the exception
			}
		},
		methods: {
			hexToRGBA(hex, alpha = 0) {
				// 移除可能存在的 #
				hex = hex.replace(/^#/, '');

				// 确保 hex 是 6 位数
				if (hex.length === 3) {
					hex = hex.split('').map(char => char + char).join('');
				}

				// 将 hex 转换为 RGB
				const r = parseInt(hex.substr(0, 2), 16);
				const g = parseInt(hex.substr(2, 2), 16);
				const b = parseInt(hex.substr(4, 2), 16);

				// 返回 rgba 字符串
				return `rgba(${r}, ${g}, ${b}, ${alpha})`;
			},
			shuffleArray(array) {
			  for (let i = array.length - 1; i > 0; i--) {
			    // 生成一个0到i之间的随机索引
			    const j = Math.floor(Math.random() * (i + 1));
			    // 交换array[i]和array[j]
			    [array[i], array[j]] = [array[j], array[i]];
			  }
			  return array;
			},
			updateDynamicStyles(color = '', type) {
				// let col = this.hexToRGBA(color)
				// let col1 = this.hexToRGBA(color, 0.5)
				// let afterstr = {
				// 	'--item-color': `linear-gradient(180deg, ${col}, ${col1})`
				// }
				
				// let bar = {
				// 	'background': color
				// }
				// if (type == 'after') return afterstr
				const arr ={
						34: 'rgba(181.0000044107437, 181.0000044107437, 181.0000044107437, 1)',
						35: 'rgba(255, 188.0000039935112, 0, 1)',
						36: 'rgba(161.0000056028366, 155.00000596046448, 240.00000089406967, 1)',
						37: 'rgba(181.0000044107437, 181.0000044107437, 181.0000044107437, 1)',
					}
				
				if (type == 'bar') return arr[color]
				// const styleSheet = document.createElement("style");
				// document.head.appendChild(styleSheet);
				// const cssRules = arr[0].reduce((cur, prev) => {
				// 	if (!cur.some(a => {
				// 			if (a) return a.afterstr.slice(6, 12) == prev.shang_color.slice(1,7)
				// 		})) {
				// 		let afterstr =
				// 			`.item-${prev.shang_color.slice(1,7)}::after{content: '';display: block;width: 133rpx;height: 60rpx;background: linear-gradient(180deg, ${this.hexToRGBA(prev.shang_color)}, ${this.hexToRGBA(prev.shang_color,0.5)}) !important;position: absolute;left: 10rpx;bottom: 0;transform: skew(-20deg);}`
				// 			let bar = `.item-${prev.shang_color.slice(1,7)} .bar {background: ${prev.shang_color} !important}`
				// 	cur.push({afterstr,bar})
				// 	}
				// 	return cur
				// }, [])
				// cssRules.forEach(item => {
				// 	styleSheet.sheet.insertRule(item.afterstr, 0);
				// 	styleSheet.sheet.insertRule(item.bar, 0);
				// })
			},
			/**
			 * 跳过动画
			 */
			skipAni(type) {
				console.log('组件触发')
				/* 隐藏动画弹窗 */
				// this.showAni = false
				// this.showVideo = false
				/* 清除动画倒计时 */
				clearTimeout(this.aniTimer)
				this.aniTimer = null
				/* 停止抽奖音乐 */
				// this.drawMusic.stop()
				this.drawMusic.pause();
				// this.drawMusic.destroy()
				this.$emit('close', type)
				// /* 播放开奖音效 */
				this.drawMusic.src = '/static/audio/open.mp3'
				this.drawMusic.seek(0);
				this.drawMusic.play();
				// this.skipMusic.seek(0)
				// this.skipMusic.play()
				// this.skipMusic.onPlay((e) => {
				// 	console.log('onPlay',e);
				// })
				// this.skipMusic.onError((res) => {
				// 	console.log(res.errMsg);
				// 	  console.log(res.errCode);
				// })
				/* 打开中奖结果弹窗 */
				// this.$refs.resPop.open()
			},

			/* 初始化动画 */
			initDraw(list, list1) {
				if (list.length > 5) {
					this.skipAni(true)
					return
				}

				let arr = []
				/* 生成符合长度的数组 */
				list.map((item, i) => {
					if (!arr[i]) {
						arr[i] = []
					}
					do {
						let dbtate = this.shuffleArray(list1)
						arr[i] = arr[i].concat(JSON.parse(JSON.stringify(dbtate)))
					} while (arr[i].length < 35)
				})
				

				/* 奖品放入数组指定位置 */
				list.map((item, i) => {
					if (i % 2 == 0) {
						arr[i][27] = Object.assign(item,{imgurl: item.goodslist_imgurl}) 
					}
					if (i % 2 != 0) {
						arr[i][32] = Object.assign(item,{imgurl: item.goodslist_imgurl}) 
					}
				})
				// try{
				// 	this.skipMusic.pause();
				// 	this.skipMusic.destroy()	
				// 	this.skipMusic = null
				// }catch(e){
				// 	//TODO handle the exception
				// }
				try {
					this.drawMusic.pause();
				} catch (e) {
					//TODO handle the exception
				}
				if (!this.drawMusic) this.drawMusic = uni.createInnerAudioContext()
				this.drawMusic.src = this.music_2
				// if (!this.skipMusic) {
				// 	this.skipMusic = uni.createInnerAudioContext()
				// 	this.skipMusic.src = this.music_1
				// }
				console.log(arr);
				/* 修改后的抽奖数组 */
				this.aniList = arr
				// this.updateDynamicStyles(arr);
				/* 重置抽奖动画dom */
				this.aniKey += 1
				/* 显示抽奖弹窗 */
				this.showAni = true
				this.drawMusic.pause();
				this.drawMusic.stop()
				this.drawMusic.seek(0)
				this.drawMusic.play()
				/* 播放抽奖音效(播放音效有bug,有时播放会失效,需要先停止再播放) */
				/* 动画倒计时 */
				this.aniTimer = setTimeout(() => {
					this.skipAni()
				}, 8300)
			},

			/**
		 计算出滚动距离
		 (width * 35)  ： 需要滚动到的元素
		 this.phoneWidth /2 ： 父元素一半的宽度
		 width/2 ： 一块元素一半的宽度
		*/
			calcDistance() {
				if (uni.getStorageSync('_view_left') && uni.getStorageSync('_view_left_1')) {
					this.distance = uni.getStorageSync('_view_left')
					this.distance1 = uni.getStorageSync('_view_left_1')
				} else {
					uni
						.createSelectorQuery()
						.in(this)
						.select('.aniFather')
						.boundingClientRect(data => {
							this.phoneWidth = data.width
						})
						.select('.aniChild')
						.boundingClientRect(data => {
							let width = data.width
							this.distance = width * 27 - this.phoneWidth / 2 + width / 2
							// console.log('滚动距离', this.distance)
							uni.setStorageSync('_view_left', this.distance)
							this.distance1 = width * 32 - this.phoneWidth / 2 + width / 2
							// console.log('滚动距离', this.distance1)
							uni.setStorageSync('_view_left_1', this.distance1)
						})
						.exec()
				}
			}
		}
	}
</script>

<style lang="scss">
	.ani-pop {
		width: 100vw;
		height: 100vh;
		box-sizing: border-box;
		// padding: 100rpx 0 100rpx;
		background: #000;
		display: flex;
		flex-flow: column nowrap;
		// justify-content: space-evenly;
		justify-content: center;
		align-items: center;
		position: fixed;
		left: 0;
		top: 0;
		z-index: 9999;

		.ani-pop-hd {
			width: 692rpx;
			height: 284rpx;
			position: relative;
			margin: 0 auto;

			// image {
			//   width: 100%;
			//   height: 424rpx;
			//   position: absolute;
			//   left: 0;
			//   top: 0;
			// }
		}

		.ani-pop-bd {
			width: 100%;
			padding: 100rpx 0 40rpx;
			margin: -100rpx 0 0;
			position: relative;

			.dot-line {
				height: 90%;
				position: absolute;
				left: 50%;
				bottom: 0;
				display: flex;
				flex-flow: column nowrap;
				justify-content: space-between;
				align-items: center;
				transform: translateX(-50%);
				z-index: 10;

				.dot {
					width: 750rpx;
					height: 70rpx;
					position: relative;

					.cc47 {
						position: absolute;
						top: -10rpx;
						left: 50%;
						transform: translate(-50%);
						width: 109.2rpx;
						height: 111.42rpx;
					}

					.cc48 {
						position: absolute;
						top: -30rpx;
						left: 50%;
						transform: translate(-50%);
						width: 109.2rpx;
						height: 111.42rpx;
					}
				}

				.line {
					width: 2rpx;
					background: #AEFFFF;
					height: calc(100% - 40rpx);
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%, -50%);
					background-size: 100% auto;
					// background-position: 0 0;
					background-position: center center;
				}
			}

			@keyframes move {
				0% {
					transform: translateX(0) translateZ(0);
				}

				100% {
					transform: translateX(var(--distance)) translateZ(0);
				}
			}

			@keyframes move1 {
				0% {
					transform: translateX(0) translateZ(0);
				}

				100% {
					transform: translateX(var(--distance1)) translateZ(0);
				}
			}

			.move {
				animation: move 8.3s 0s both;
			}

			.move1 {
				animation: move1 8.3s 0s both;
			}

			.row-item-34::after {
				background: linear-gradient(180deg, rgba(255, 158.00000578165054, 122.00000032782555, 0), rgba(255, 50.000000819563866, 85.0000025331974, 0.5))
			}
			.row-item-35::after {
				background: linear-gradient(180deg, rgba(255, 188.0000039935112, 0, 0), rgba(240.00000089406967, 166.00000530481339, 0, 0.5))
			}
			.row-item-36::after {
				background: linear-gradient(180deg, rgba(161.0000056028366, 155.00000596046448, 240.00000089406967, 0), rgba(127.00000002980232, 101.00000157952309, 229.00000154972076, 0.5))
			}
			.row-item-37::after {
				background: linear-gradient(180deg, rgba(181.0000044107437, 181.0000044107437, 181.0000044107437, 0), rgba(146.00000649690628, 146.00000649690628, 146.00000649690628, 0.5))
			}
			
			.row {
				// width: 100%;
				height: 133rpx;
				display: flex;
				will-change: transform;

				&-item {
					width: 100%;
					height: 100%;
					position: relative;
					display: flex;
					justify-content: center;
					align-items: center;

					&::after {
						content: '';
						display: block;
						width: 133rpx;
						height: 60rpx;
						// background: var(--item-color);
						position: absolute;
						left: 10rpx;
						bottom: 0;
						transform: skew(-20deg);
					}

					// .bar {
					// 	background: #ff5944;
					// }

					.pic {
						width: 133rpx;
						height: 133rpx;
						box-sizing: border-box;
						// padding: 20rpx;
						position: relative;
						z-index: 2;
						background-size: 110rpx 110rpx;
						background-repeat: no-repeat;
						background-position: center center;
					}

					.bar {
						position: absolute;
						bottom: 0;
						left: 0;
						width: 100%;
						height: 6rpx;
						// transform: skew(-10deg);
						// box-shadow: inset 0rpx 5rpx 1rpx 0rpx rgba(255, 255, 255, 0.23),
						//   inset 0rpx 0rpx 5rpx 0rpx rgba(0, 0, 0, 0.5);
					}
				}
			}
		}

		.ani-pop-ft {
			margin: 80rpx 0 0;
			width: 198rpx;
			height: 80rpx;
			background: #113441;
			color: var(--color);
			border-radius: 256rpx 256rpx 256rpx 256rpx;
			border-radius: 41rpx 41rpx 41rpx 41rpx;
			border: 2rpx solid var(--gray-line);
			display: flex;
			justify-content: center;
			align-items: center;

			// font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			z-index: 99999;
		}
	}

	.allDrawn {
		width: 600rpx;
		margin: 0 auto;
		height: 113rpx;
		display: flex;
		align-items: center;

		.pic {
			width: 118rpx;
			height: 117rpx;
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			overflow: hidden;
			flex-shrink: 0;

			>image {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>